/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.icee.myth.server.index;

import com.icee.myth.log.GameLogger;
import com.icee.myth.log.message.FileDebugGameLogMessage;
import com.icee.myth.log.message.builder.GameLogMessageBuilder;
import com.icee.myth.server.levelup.HumanRanksConfig;

/**
 * 按军衔记录内存中玩家（全局索引）
 * @author liuxianke
 */
public class PlayerIdsOfRanks {
    public final PlayerIdsOfRank[] playerIdsOfRanks;  // 以军衔为下标记录每个军衔中存在的内存中玩家id

    public static final PlayerIdsOfRanks INSTANCE = new PlayerIdsOfRanks();

    private PlayerIdsOfRanks() {
        playerIdsOfRanks = new PlayerIdsOfRank[HumanRanksConfig.INSTANCE.maxRank];
    }

    public PlayerIdsOfRank getPlayerIdsOfRank(int rank) {
        return playerIdsOfRanks[rank - 1];
    }

    public void addPlayerId(int rankLv, int playerId) {
        if ((rankLv > 0) && (rankLv <= HumanRanksConfig.INSTANCE.maxRank)) {
            if (playerIdsOfRanks[rankLv - 1] == null) {
                playerIdsOfRanks[rankLv - 1] = new PlayerIdsOfRank();
            }
            
            playerIdsOfRanks[rankLv - 1].add(playerId);
        } else {
            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                    "Player[" + playerId + "] rank[" + rankLv + "] out of range when add to rank index."));
        }
    }

    public void removePlayerId(int rankLv, int playerId) {
        if ((rankLv > 0) && (rankLv <= HumanRanksConfig.INSTANCE.maxRank)) {
            if (playerIdsOfRanks[rankLv - 1] != null) {
                playerIdsOfRanks[rankLv - 1].remove(playerId);

                if (playerIdsOfRanks[rankLv - 1].count() == 0) {
                    playerIdsOfRanks[rankLv - 1] = null;
                }
            } else {
                GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                        FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                        "Player-ids of rank[" + rankLv + "] is empty when remove player[" + playerId + "]."));
            }
        } else {
            GameLogger.getlogger().log(GameLogMessageBuilder.buildFileDebugGameLogMessage(
                    FileDebugGameLogMessage.DebugLogType.DEBUGLOGTYPE_ERROR,
                    "Player[" + playerId + "] rank[" + rankLv + "] out of range when remove from rank index."));
        }
    }
}
